<?php


namespace app\api\controller;

use app\api\model\User as UserModel;
use app\api\model\Book as BookModel;
use app\api\model\Order as OrderMdeol;
use app\api\model\OrderItem as OrderItemModel;
use app\api\model\Wallet as WalletModel;
use think\Db;

/***
 * 订单管理控制器
 * Class Order
 * @package app\api\controller
 */
class Order extends Base
{

    /***
     * Desc:直接购买书籍
     * User: HAIYUN
     * Date: 2022/2/25 14:37
     */
    public function purchase() {
        //根据token获取uid
        $uid = $this->getCurrentTokenVar("uid");
        //根据uid查找用户数据，判断是否存在
        $userModel = new UserModel();
        $user      = $userModel->where("id", $uid)->find();
        if (!$user) {
            $this->return_msg("20004", "用户不存在", []);
        }
        //校验参数
        $rules = [
            ['book_id', 'require|number', '10001|10002'],
            ['number', 'require', '10001'],
        ];
        $msg   = $this->validate($this->params, $rules);
        if ($msg !== true) $this->return_msg($msg, '参数错误');
        //过滤不必要的参数
        $safe_data = $this->getDataByRule($this->params, $rules);
        $bookModel = new BookModel();
        $book_info = $bookModel->where('id',$this->params['book_id'])->find();
        if(!$book_info)
            $this->return_msg("20004","未查询到该书籍信息",[]);
        $payment = $this->sum_money($book_info,$safe_data['number']);//计算支付金额
        $uuid = $this->get_order_uuid();
        $order_data = [
            'uuid' => $uuid,
            'payment' => $payment,
            'status' => 0,
            'user_id' => $uid,
            'buyer_nick' => $user['nick_name'],
            'is_buyer' => 1,
        ];
        $orderMdeol = new OrderMdeol();
        $orderItemModel = new OrderItemModel();
        Db::startTrans();//开启事务
        try {
            //1. 生成购买订单
            $orderMdeol->add($order_data);
            //组装订单详情数据
            $order_item_data = $this->get_item_data($book_info,$uuid);
            $order_item_data['num'] = $safe_data['number'];
            $order_item_data['total_fee'] = $payment;
            //2. 生成订单详情
            $orderItemModel->add($order_item_data);
            //减少商品数量
            $book_num = $book_info['number'] - $safe_data['number'];
            $bookModel->edit(['number'=> $book_num],['id'=>$safe_data['book_id']]);
            //3. 付款
            $walletModel = new WalletModel();
            $wallet = $walletModel->where('user_id',$uid)->find();
            if(!$wallet){
                Db::rollback();
                $this->return_msg("20006","未查询到该用户钱包信息,付款失败",[]);
            }
            $balance = $wallet['money'] - $payment;
            if($balance < 0){
                Db::rollback();
                $this->return_msg("20006","余额不足,付款失败",[]);
            }
            $walletModel->edit(['money'=>$balance],['user_id'=>$uid]);
            //修改订单状态为已付款
            $orderMdeol->edit(['status'=>2],['user_id'=>$uid]);
            //商家余额增加
            $owner_id = $book_info['user_id'];
            $owner_wallet = $walletModel->where(['user_id'=>$owner_id])->find();
            if(!$owner_wallet){
                Db::rollback();
                $this->return_msg("20006","未查询到商户钱包信息",[]);
            }
            $owner_balance = $owner_wallet['money'] + $payment;
            $walletModel->edit(['money'=> $owner_balance],['user_id'=>$owner_id]);
            //增加卖家订单
            $owner_data = $order_data;
            $owner_data['user_id'] = $owner_id;
            $owner_data['is_buyer'] = 0;
            $owner_data['status'] = 2;
            $orderMdeol->data($owner_data,true)->isUpdate(false)->save();
            // 提交事务
            Db::commit();
        }catch (\Exception $e){
            //回滚事务
            Db::rollback();
            $this->return_msg('20006',$e->getMessage(),[]);
        }
        $this->return_msg('00000','购买成功',$payment);
    }


    /***
     * Desc:计算支付金额
     * User: HAIYUN
     * Date: 2022/2/25 14:52
     */
    private function sum_money($book_info,$buy_number) {
        //验证购买数量与商品数量的关系,商品数量不足时不允许购买
//        $buy_number = $book_info['number'] <= $buy_number ? $book_info['number'] : $buy_number;
        if($buy_number > $book_info['number']) $this->return_msg("20002","商品库存不足,请修改购买数量",[]);
        //计算折扣
        //....
        $payment = $buy_number * $book_info['price'];
        return $payment;
    }

    /***
     * Desc:组装订单详情数据
     * User: HAIYUN
     * Date: 2022/2/25 15:38
     */
    private function get_item_data($book_info,$uuid) {
        $item_data = [
            'item_id' => $book_info['id'],
            'order_uuid' => $uuid,
            'title' => $book_info['book_name'],
            'price' => $book_info['price'],
            'pic_path' => $book_info['img']
        ];
        return $item_data;
    }

    /***
     * Desc:获取订单列表
     * User: HAIYUN
     * Date: 2022/2/26 14:05
     */
    public function myOrder() {
        //根据token获取uid
        $uid = $this->getCurrentTokenVar("uid");
        //根据uid查找用户数据，判断是否存在
        $userModel = new UserModel();
        $user      = $userModel->where("id", $uid)->find();
        if (!$user) {
            $this->return_msg("20004", "用户不存在", []);
        }
        $orderModel = new OrderMdeol();
        $order_list = $orderModel->where('user_id',$uid)->select();
        //遍历查询订单情况
        $return_list = [];
        $orderItemModel = new OrderItemModel();
        foreach ($order_list as $k => $v){
            //根据uuid查询订单详情
            $item = $orderItemModel->where('order_uuid',$v['uuid'])->find();
            $return_list[$k]['id'] = $item['id'];//订单id
            $return_list[$k]['uuid'] = $item['order_uuid'];//订单号
            $return_list[$k]['num'] = $item['num'];//购买/出售数量
            $return_list[$k]['title'] = $item['title'];//商品名称
            $return_list[$k]['total_fee'] = $item['total_fee'];//总花费
            $return_list[$k]['is_buyer'] = $v['is_buyer'];//是否购买者
        }
        $this->return_msg('00000','查询订单成功',$return_list);
    }

    /***
     * Desc:查询订单(订单号)
     * User: HAIYUN
     * Date: 2022/2/26 15:54
     */
    public function getOrderByUUID() {
        //根据token获取uid
        $uid = $this->getCurrentTokenVar("uid");
        //根据uid查找用户数据，判断是否存在
        $userModel = new UserModel();
        $user      = $userModel->where("id", $uid)->find();
        if (!$user) {
            $this->return_msg("20004", "用户不存在", []);
        }
        //校验参数
        $rules = [
            ['uuid', 'require', '10001'],
        ];
        $msg   = $this->validate($this->params, $rules);
        if ($msg !== true) $this->return_msg($msg, '参数错误');
        //过滤不必要的参数
        $safe_data = $this->getDataByRule($this->params, $rules);
        $orderItemModel = new OrderItemModel();
        $data = $orderItemModel->where('order_uuid',$safe_data['uuid'])->find();
        $this->return_msg('00000','查询订单详情成功',$data);
    }

}